#!/bin/bash

file_in=$1
file_out="pkg_name.log"
file_tmp="tmp.log"
# 初始化一个空数组用于存储 "level: 1" 的包名
src_names=()

function rpm_dep_list()
{
    if [ $(cat "$file_in" | wc -l) -eq 0 ]; then
        echo "WARNNING: input file rpm_list is NULL."
        exit 1
    fi
    # 查询编译依赖
    cat $file_in | xargs -I {} rpm-dep -B {} -t json -l 2
    # 查询安装依赖
    cat $file_in | xargs -I {} rpm-dep -I {} -t json -l 2
    
    if [ $? -eq 0 ]; then
        echo "====== rpm_dep successful ======"
    fi
}

function rpm_dep_list_clean()
{
    rm dep*
}

function get_list()
{
    # 确保已安装"jq"，用于解析json
    if ! command -v jq >/dev/null 2>&1; then
        echo -e "\033[1;31m [Warning: jq is not installed. Attempting to 'dnf install jq' ...] \033[0m"
        if sudo dnf install jq -y -q; then
            echo -e "\033[1;31m [INFO: 'dnf install jq' successfully.] \033[0m"
        else
            echo "Failed to install jq. Please install jq manually using your package manager."
            exit 1
        fi
    fi

    # 清空或创建 file_out 文件
    rm -f $file_out
    :> $file_out
    :> $file_tmp

    # 查找 json
    json_files=$(ls | grep -E '\.json$')

    # 遍历 json
    for file in $json_files; do
        # 提取 "level: 1" 的包名
        level1_package=$(jq -r 'select(.level==1) | .src_name' $file)
        src_names+=("$level1_package")
        # 提取 "level: 2" 的包名
        jq -r '.next[] | select(.level==2) | .src_name' $file >> $file_tmp
    done
    # cat $file_tmp | sort -u > $file_out
    sort -u $file_tmp -o $file_tmp

    # 过滤掉 "level: 1" 的包名，源码包本身  无需重编
    for src_name in "${src_names[@]}"; do
        grep -v "^$src_name$" $file_tmp > $file_out
    done

    rm -f $file_tmp
}

# 如果传入参数1，需要执行rpm_dep查询，得到file_out（待release +1软件包名单）
if [ "$#" -ge 1 ]; then
    rpm_dep_list
    get_list
    rpm_dep_list_clean
    echo -e "\033[1;31m [Note: Before using auto_release.sh, please check pkg_name.log!!!] \033[0m"
elif [ $(cat "$file_out" | wc -l) -eq 0 ]; then
    echo "WARNNING: $file_out is NULL, no package."
else
    echo "ERROR: No arguments provided. Skipping rpm_dep function."
fi
